package com.chenjun.core.service.sys.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.chenjun.common.Constant;
import com.chenjun.common.bean.Pagination;
import com.chenjun.common.model.DataGridModel;
import com.chenjun.common.model.DataGridSortModel;
import com.chenjun.core.dao.generator.entity.SysResource;
import com.chenjun.core.dao.generator.mapper.SysResourceMapper;
import com.chenjun.core.dao.module.SysResourceRelationMapper;
import com.chenjun.core.service.sys.SysResourceService;
import com.chenjun.core.vo.sys.TreeVo;

@SuppressWarnings("serial")
@Service
@Transactional
public class SysResourceServiceImpl implements SysResourceService {
	private static final Logger logger = Logger.getLogger(SysResourceServiceImpl.class);
	@Autowired
	private SysResourceMapper sysResourceMapper;
	@Autowired
	private SysResourceRelationMapper sysResourceRelationMapper;

	public SysResource get(String id) {
		return sysResourceMapper.selectByPrimaryKey(id);
	}

	public int create(SysResource record) {
		return sysResourceMapper.insert(record);
	}

	public int delete(String id) {
		return sysResourceMapper.deleteByPrimaryKey(id);
	}

	public int update(SysResource record) {
		return sysResourceMapper.updateByPrimaryKey(record);
	}

	public int createOrUpdate(SysResource record) {
		int rows = 0;
		if (StringUtils.isBlank(record.getId())) {
			record.setCreatedTime(Calendar.getInstance().getTime());
			rows = sysResourceMapper.insert(record);
		} else {
			rows = sysResourceMapper.updateByPrimaryKeySelective(record);
		}
		return rows;
	}

	public int doCountByCondition(DataGridModel param) {
		return sysResourceRelationMapper.countByCondition(param);
	}

	public List<SysResource> doListByCondition(DataGridModel param) {
		return sysResourceRelationMapper.selectByCondition(param);
	}

	public Pagination doPagination(DataGridModel param) {
		Pagination vo = new Pagination();
		List<SysResource> list = sysResourceRelationMapper.selectByCondition(param);
		param.setStart(0);
		param.setRows(0);
		int size = sysResourceRelationMapper.countByCondition(param);
		vo.setAaData(list);
		vo.setiTotalRecords(size);
		vo.setsEcho(param.getPage());
		vo.setiTotalDisplayRecords(size);
		return vo;
	}

	public List<TreeVo> findAllResourcesForTree(DataGridModel param) {
		param.getSortBy().add(new DataGridSortModel("sort_num", DataGridSortModel.ASC));
		List<SysResource> resources = doListByCondition(param);
		Object pflag = param.getParams().get("pflag");
		if (null != pflag && Boolean.valueOf(pflag.toString())) {
			SysResource res = new SysResource();
			res.setId("0");
			res.setName("江苏晨俊智能科技信息服务平台");
			res.setParentId("-1");
			res.setSortNum(0);
			res.setType("1");
			resources.add(res);
		}

		List<TreeVo> dtoList = modelToTreeDtoList(param.getParams(), resources);
		return getSliderResult(pflag, param.getParams().get("treeId").toString(), dtoList);
	}

	/**
	 * 将resource 的list转化成dto的list
	 * 
	 * @param map
	 * @param resources
	 * @return List<TreeDto>
	 */
	private List<TreeVo> modelToTreeDtoList(Map<String, Object> map, List<SysResource> resources) {
		int size = resources.size();
		List<TreeVo> dtoList = new ArrayList<TreeVo>(size);
		for (int i = 0; i < size; i++) {
			TreeVo TreeDto = modelToTreeDto(map, resources.get(i));
			dtoList.add(TreeDto);
		}
		return dtoList;
	}

	/**
	 * 
	 * 根据resource的id获取资源名称
	 * 
	 * @param id
	 * @return String
	 */
	public String getResourceNameByUrl(String url) {
		Map<String, Object> params = new HashMap<String, Object>(1);
		params.put("url", url);
		List<SysResource> resources = sysResourceRelationMapper.seleceByMapParams(params);
		if (!CollectionUtils.isEmpty(resources)) {
			return resources.get(0).getName();
		}
		return "";
	}

	/**
	 * 功能dto转换树结构dto
	 * 
	 * @param map
	 * @param resource
	 * @return TreeDto
	 */
	private TreeVo modelToTreeDto(Map<String, Object> map, SysResource resource) {
		Map<String, Boolean> stateMap = new HashMap<String, Boolean>(0);
		TreeVo treeDto = new TreeVo();
		String prefix = "";// map.get("treeId").toString(); prefix + "_" +
		if (!StringUtils.isBlank(prefix)) {
			treeDto.setId(resource.getId());
		} else {
			treeDto.setId(resource.getId());
		}
		treeDto.setText(resource.getName());
		if ("1".equals(resource.getType())) {
			treeDto.setType(Constant.Tree.FILE_TYPE.toString());
		}
		// 节点是否可选
		String isDisable = map.get("disable").toString();
		if ("true".equals(isDisable)) {
			// 全不可选
			stateMap.put(Constant.Tree.STATE_DISABLED.toString(), true);
		}
		if (!stateMap.isEmpty()) {
			treeDto.setState(stateMap);
		}
		treeDto.setFid(resource.getParentId());
		return treeDto;
	}

	public List<TreeVo> getSliderResult(Object pflag, String prefix, List<TreeVo> src) {
		List<TreeVo> parents = new ArrayList<TreeVo>(0);
		List<TreeVo> others = new ArrayList<TreeVo>(0);
		// 遍历list，将父节点为0的add到list中
		// 遍历list，将父节点不为0的add到list中
		String topfid = Constant.Tree.TOP_FID.toString();
		if (null != pflag && Boolean.valueOf(pflag.toString())) {
			topfid = Constant.Tree.RESCOURCE_TOP_FID.toString();
		}
		for (TreeVo dto : src) {
			TreeVo result = dto;
			if (topfid.equals(dto.getFid())) {
				result.setChildren(new ArrayList<TreeVo>(0));
				parents.add(result);
			} else {
				others.add(result);
			}
		}
		buildSliderTree(prefix, parents, others);
		return parents;

	}

	private void buildSliderTree(String prefix, List<TreeVo> parents, List<TreeVo> surplus) {
		List<TreeVo> record = new ArrayList<TreeVo>();
		for (int i = 0; i < parents.size(); i++) {
			TreeVo vi = parents.get(i);
			for (int j = 0; j < surplus.size(); j++) {
				TreeVo inVi = surplus.get(j);
				String nodeId = vi.getId();
				if (!StringUtils.isBlank(prefix) && nodeId.startsWith(prefix)) {
					nodeId = nodeId.substring(prefix.length() + 1);
				}
				if (nodeId.equals(inVi.getFid())) {
					if (vi.getChildren() == null) {
						vi.setChildren(new ArrayList<TreeVo>());
					}
					vi.getChildren().add(inVi);
					record.add(inVi);
				}
			}
			surplus.removeAll(record);
		}
		if (surplus.isEmpty() || record.isEmpty()) {
			return;
		} else {
			buildSliderTree(prefix, record, surplus);
		}
	}
}